<?php
/**
 * @since          1.0
 */

namespace app\common\model;

use think\Model;
use think\model\concern\SoftDelete;
use Xin\Auth\UserProviderInterface;
use xin\iplocation\IpLocation;
use Xin\Thinkphp5\Auth\UserProvider;

/**
 * @property-read int                id
 * @property string                  nickname
 * @property string                  gender
 * @property string                  avatarUrl
 * @property string                  language
 * @property string                  country
 * @property string                  province
 * @property string                  city
 * @property int                     energy
 * @property int                     pid
 * @property int                     origin
 * @property int                     sys_time
 * @property string                  openid
 * @property int                     login_count
 * @property int                     login_time
 * @property int                     login_ip
 * @property int                     is_store
 */
class User extends Model implements UserProviderInterface{

	use SoftDelete, UserProvider;

	/**
	 * @var int
	 */
	protected $defaultSoftDelete = 0;

	/**
	 * 创建时间
	 *
	 * @var string
	 */
	protected $createTime = 'create_time';

	/**
	 * 更新时间
	 *
	 * @var string
	 */
	protected $updateTime = 'update_time';

	/**
	 * @var \xin\iplocation\IpLocation
	 */
	private static $IPInstance;

	/**
	 * 关联商家信息
	 *
	 * @return \think\model\relation\HasOne
	 */
	public function store(){
		return $this->hasOne("Store", "uid");
	}

	/**
	 * 获取性别
	 *
	 * @return mixed
	 */
	protected function getGenderTextAttr(){
		return [
				   '1' => '男',
				   '2' => '女',
			   ][$this->gender] ?? '未知';
	}

	/**
	 * 获取来源标题
	 *
	 * @return mixed
	 */
	protected function getSourceTextAttr(){
		return [
				   '1' => '微信',
				   '2' => '支付宝',
			   ][$this->origin];
	}

	/**
	 * 获取IP地址
	 *
	 * @param $val
	 * @return string
	 */
	protected function getLoginIpAttr($val){
		return long2ip($val);
	}

	/**
	 * 获取IP地址
	 *
	 * @return string
	 */
	protected function getLoginIpAddrAttr(){
		if(!$this->login_ip) return "未知";

		$ip = self::getLocationInstance();
		$val = $ip->getLocation($this->login_ip);

		return $val['country'].$val['area'];
	}

	/**
	 * 获取IP解析类实例
	 *
	 * @return IpLocation
	 */
	private static function getLocationInstance(){
		if(is_null(self::$IPInstance)){
			self::$IPInstance = new IpLocation();
		}
		return self::$IPInstance;
	}

	/**
	 * @inheritDoc
	 */
	public function validatePassword($user, $password){
		throw new \RuntimeException('未实现！');
	}
}
